from flask import Blueprint,current_app,send_file, jsonify, request
from tts.zijie.zijie_tts import combine_texts_to_audio
from config import SYSTEM_CONFIG
from tts.zijie.async_zijie_tts import main
import asyncio
import tts.baidu.baidu_syn as baidu_syn
import asr.baidu.baidu_rec as baidu_rec
import wave
import llm.doubao as doubao
import json
# mqtt形式发送音频数据
blueprint = Blueprint('/', __name__, url_prefix='/')
# 用于存储接收到的二进制数据
@blueprint.route("/upload", methods=['GET', 'POST'])
def upload():
    data_list = current_app.config['DATA_LIST']
    all_data = b''.join(data_list)  
    # 将接收到的二进制数据写入 WAV 文件
    try:
        with wave.open('./audio/received_audio.wav', 'wb') as wf:
            wf.setnchannels(1)  
            wf.setsampwidth(2)  
            wf.setframerate(8000)  
            wf.writeframes(all_data)

        data_list.clear()  

    except Exception as e:
        print(f"写入 WAV 文件时出错: {e}")  

    return jsonify({'status': 'success','message': '数据接收成功'})



# tcp形式发送音频数据
@blueprint.route('/tcp', methods=['GET', 'POST'])
def tcp():
    data_list = current_app.config['DATA_LIST']
    while True:
        data = request.stream.read(3000)  # 每次读取 2048 字节
        if not data:
            break
        else:
            data_list.append(data)  # 只有在读取到数据时才添加

    print(f"接收到的数据段数量: {len(data_list)}")  # 打印接收到的数据段数量

    all_data = b''.join(data_list)  # 将列表中的数据拼接
    print(f"接收到的总数据长度: {len(all_data)}")  # 打印接收到的总数据长度

    # 将接收到的二进制数据写入 WAV 文件
    try:
        with wave.open('./audio/received_audio.wav', 'wb') as wf:
            wf.setnchannels(1)  # 单声道
            wf.setsampwidth(2)  # 16 位（2 字节）采样宽度
            wf.setframerate(16000)  # 采样率 8000Hz
            wf.writeframes(all_data)

    except Exception as e:
        print(f"写入 WAV 文件时出错: {e}")  # 打印写入文件时的错误

    return jsonify({'status': 'success','message': '数据接收成功'})



# 向esp32发送合并完成后的音频二进制
@blueprint.route('/asr_result', methods=['GET', 'POST'])
def asr_result():
   
    with current_app.app_context():  
        try:
            results = baidu_rec.main('./audio/received_audio.wav')
            # 将 JSON 字符串解析为 Python 对象
            parsed_data = json.loads(results)
            print(parsed_data['result'][0])
            q = doubao.main(parsed_data['result'][0])
            print(q)
            if SYSTEM_CONFIG['SPEECH_TYPE'] == 'baidu':
                baidu_syn.main(q)
            elif SYSTEM_CONFIG['SPEECH_TYPE'] == 'zijie':
                if SYSTEM_CONFIG['SPEECH_METHOD'] == 'async_zijie_tts':
                    async def call_from_other_file():
                        await main(q)
                    asyncio.run(call_from_other_file())
                elif SYSTEM_CONFIG['SPEECH_METHOD'] == 'zijie_tts':
                    combine_texts_to_audio(q)

             
            
            file_path = './audio/temp_output.wav'
            return send_file(file_path, as_attachment=True)

        except Exception as e:
            return jsonify({'status': 'error', 'message': str(e)})